package com.Gourmet;

import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

import com.beans.MiLocalizacionDTO;
import com.beans.RestauranesDTO;
import com.driving.DrivingDirections;
import com.driving.DrivingDirectionsFactory;
import com.driving.Placemark;
import com.driving.Route;
import com.driving.DrivingDirections.Mode;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;


public class Mapa extends MapActivity implements DrivingDirections.IDirectionsListener{	
	
	private MapController mcontrol;
	private GeoPoint GeoPointRestaurante;
	private GeoPoint GeoPointMiLocalizacion;
	private Location localizacion;
	private RestauranesDTO restaurante = null;
	private  HelloItemizedOverlay itemizedoverlay = null;
	private List<Overlay> mapOverlays = null;
	private MyOverlay myOverlay = new MyOverlay();
	private Context contexto=null;
	//MapView mapV;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.maparestaurant);
          
        MapView mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        mapView.displayZoomControls(true);
   
        mcontrol = mapView.getController();
        
        //Capturamos los datos de la actividad anterior
        Bundle extras = getIntent().getExtras();            
               
        if (extras != null) {   
        	contexto = mapView.getContext();
            restaurante = extras.getParcelable(Detalle.MyKey);
            MiLocalizacionDTO milocalizacion = extras.getParcelable(Detalle.MyKeyLocalizacion);
            //Instacncion mi itemoverlay
            mapOverlays = mapView.getOverlays();
            Drawable drawable = this.getResources().getDrawable(R.drawable.icono);
            itemizedoverlay = new HelloItemizedOverlay(drawable, mapView.getContext());
                 
            GeoPointRestaurante = new GeoPoint((int)(restaurante.getLatitud()*1E6), (int)(restaurante.getLongitud()*1E6));		        
	        mcontrol = mapView.getController();
	        mcontrol.animateTo(GeoPointRestaurante);
	        mcontrol.setZoom(15);
	      
	    	GeoPointMiLocalizacion = new GeoPoint((int)(milocalizacion.getLatitud()*1E6) ,(int) (milocalizacion.getLongitud()*1E6)); 
	     
            OverlayItem overlayitem = new OverlayItem(GeoPointRestaurante, restaurante.getDescripcion(), restaurante.getDireccion());
        	OverlayItem overlayitemMiLocalizacion = new OverlayItem(GeoPointMiLocalizacion, "Estoy aca","");
        	
            itemizedoverlay.addOverlay(overlayitem);         	        
            itemizedoverlay.addOverlay(overlayitemMiLocalizacion); 
            mapOverlays.add(itemizedoverlay);
            
            //Trazamos la ruta
            DrivingDirections.Mode mode = Mode.DRIVING; 
            DrivingDirections directions = DrivingDirectionsFactory.createDrivingDirections(); 
            directions.driveTo(GeoPointMiLocalizacion, GeoPointRestaurante, mode, this);
        }
                
      //Obtengo mi geolocalizacion
    	String serviceString = Context.LOCATION_SERVICE; 
    	LocationManager locationManager =  (LocationManager)getSystemService  (serviceString); 
    	String proovedor = LocationManager.GPS_PROVIDER; 
    	
    	locationManager.requestLocationUpdates(proovedor, 0, 0, new LocationListener() {
			
			public void onStatusChanged(String provider, int status, Bundle extras) {
				// TODO Auto-generated method stub
				
			}
			
			public void onProviderEnabled(String provider) {
				// TODO Auto-generated method stub
				
			}
			
			public void onProviderDisabled(String provider) {
				// TODO Auto-generated method stub
				
			}
			
			public void onLocationChanged(Location location) {
				// TODO Auto-generated method stub
				localizacion = location; 
				posicion(); 

			}
		}
    	);
 
    }
    
    private void posicion() 
    { 
    if (localizacion!=null) 
    { 
    itemizedoverlay.clearOverlay();
    mapOverlays.clear();
    GeoPointMiLocalizacion = new GeoPoint((int)(localizacion.getLatitude()*1E6),(int)( localizacion.getLongitude()*1E6)); 
    mcontrol.animateTo(GeoPointRestaurante);
    mcontrol.setZoom(15);
    OverlayItem overlayitemRestaurante = new OverlayItem(GeoPointRestaurante, restaurante.getDescripcion(), restaurante.getDireccion());
    OverlayItem overlayitemMiLocalizacion = new OverlayItem(GeoPointMiLocalizacion, "Estoy aca","");
    itemizedoverlay.addOverlay(overlayitemRestaurante);
    itemizedoverlay.addOverlay(overlayitemMiLocalizacion);
    mapOverlays.add(itemizedoverlay);	
    
    //Trazamos la ruta
    DrivingDirections.Mode mode = Mode.DRIVING; 
    DrivingDirections directions = DrivingDirectionsFactory.createDrivingDirections(); 
    directions.driveTo(GeoPointMiLocalizacion, GeoPointRestaurante, mode, this);
    
     } 
    }
    

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	public void onDirectionsAvailable(Route route, Mode mode) {
		myOverlay.setRoute(route, mode);
		mapOverlays.add(myOverlay);
	}

	public void onDirectionsNotAvailable() {
		// TODO Auto-generated method stub
		
	}
	
	
	//Clase MyOverlay
	class  MyOverlay extends Overlay{
		
		private Route route;
		private Mode mode;
		
		
		public Route getRoute() {
			return route;
		}


		public void setRoute(Route route, Mode mode) {
						this.route = route;
			this.mode = mode;
		}


		@Override
		public void draw(Canvas canvas, MapView mapView, boolean shadow) {
			// TODO Auto-generated method stub
			super.draw(canvas, mapView, shadow);
			if (route != null) {
				drawRoute (route.getGeoPoints(), canvas, mapView);
				/*if (startIcon != 0 && middleIcon != 0 && endIcon != 0) {
					drawPlacemarks (route.getPlacemarks(), canvas, mapView);
					}*/
				}
		}
		
		private void drawRoute(List geoPoints, Canvas canvas, MapView mapView)
		{
		for (int i = 0; i < geoPoints.size() - 1; i++)
		{
		// Convert the starting geographical point coordinates to screen coordinates.
		//
		GeoPoint startGeoPoint = (GeoPoint) geoPoints.get (i);
		Point startScreenPoint = new Point ();
		mapView.getProjection().toPixels(startGeoPoint, startScreenPoint);

		// Convert the ending geographical point coordinates to screen coordinates.
		//
		GeoPoint endGeoPoint = (GeoPoint) geoPoints.get (i + 1);
		Point endScreenPoint = new Point ();
		mapView.getProjection().toPixels(endGeoPoint, endScreenPoint);

		// Draw a joining line between the starting and the ending points.
		//
		Paint paint = new Paint();
		paint.setStrokeWidth(5);
		paint.setAntiAlias(true);
		if ((mode != null) && (mode == Mode.DRIVING)) {
		paint.setARGB(64, 0, 0, 255);
		}
		else {
		paint.setARGB(96, 0, 0, 0);
		paint.setPathEffect(new DashPathEffect(new float[]{8, 4}, 1));
		}
		canvas.drawLine(startScreenPoint.x, startScreenPoint.y, endScreenPoint.x, endScreenPoint.y, paint);
		
		}
		}	
		
	/*	//DIBUJANDO LOS PLACEMARKS
		private void drawPlacemarks(List placemarks, Canvas canvas, MapView mapView)
		{
		for (int i = 0; i < placemarks.size(); i++)
		{
		// Convert the placemark geographical location to screen coordinates.
		//
		Placemark p = (Placemark)placemarks.get(i);
		GeoPoint geoPoint =  p.getLocation();
		Point screenPoint = new Point();
		mapView.getProjection().toPixels(geoPoint, screenPoint);

		// Select the placemark to use (start, middle or end points) and draw its bitmap
		// on the screen.
		//
		Bitmap place;
		int placemarkSize = placemarks.size();
		if (i == 0) {
		// Start placemark.
		//
		place = BitmapFactory.decodeResource(contexto.getResources(), startIcon);
		canvas.drawBitmap(place, 0, 0, null);
		}
		else if (i == placemarkSize-1) {
		// End placemark.
		//
		place = BitmapFactory.decodeResource(contexto.getResources(), endIcon);
		canvas.drawBitmap(place, 50, 50, null);
		}
		else {
		// Middle placemark.
		//
		place = BitmapFactory.decodeResource(contexto.getResources(), middleIcon);
		canvas.drawBitmap(place, 70, 70, null);
		}
		}
		}*/
		
		
	}
}
	
